<template>
  <div v-loading="loading" class="train">
    <div class="box">
      <div ref="certificate" class="certificate" :style="form.backgroundStyle">
        <div ref="people" class="img_box">
          <img src="@/assets/images/people_default.png" alt="">
        </div>
        <div ref="info" class="info">
          <p>学员姓名：______________________</p>
          <p>培训名称：______________________</p>
          <p>培训日期：______________________</p>
          <p>培训地点：______________________</p>
        </div>
      </div>
    </div>
    <div class="control">
      <div style="width: 590px" class="gl_mt_10">
        <el-row type="flex" justify="space-between">
          <el-col class="title_name gl_ml_20" :span="6">更换背景图：</el-col>
          <el-col class="gl_mr_20" align="right" :span="4">
            <el-button :loading="resetLoading" type="text" size="small" @click="resetImage">
              <span class="gl_color_error gl_fs_14">恢复原图</span>
            </el-button>
          </el-col>
        </el-row>
        <div class="box">
          <el-upload
            class="upload_img"
            :action="action"
            :before-upload="beforeUpload"
            :http-request="upload"
            :auto-upload="true"
            :show-file-list="false"
            accept=".jpg,.png,.jpeg"
          >
            <el-button :loading="uploadLoading" type="text" size="mini">+更换背景图</el-button>
          </el-upload>
          <span class="gl_fs_12 gl_color_grey">只能上传jpg/png文件，且不超过800kb</span>
        </div>
      </div>
      <div class="gl_mt_15 gl_pl_5">
        <el-button :loading="buLoading" type="primary" size="mini" @click="exportTemplate()">导出参训证</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/lib/auth';
import axios from 'axios';
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';
import {
  api_GET_TrainReportTemplateSettingEntryCardSettingTrainningId, // 获取参训证配置信息
  api_DELETE_TrainReportTemplateSettingEntryCardSettingTrainningId, // 恢复默认
  api_PUT_TrainReportTemplateSettingEntryCardSetting // 更新配置
} from '@/extend/api/trainswaggerApi/app.js';
export default {
  data() {
    return {
      loading: false,
      buLoading: false, // 生成模板的loading
      uploadLoading: false, // 上传图片的loading
      resetLoading: false, // 恢复默认设置的loading
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`,
      tokenInfo: getToken(),
      file: '', // 上传的图片
      form: {
        backgroundStyle: {}
      } // 参训证配置
    };
  },
  created() {
    this.getSetting();
  },
  methods: {
    // 获取参训证设置
    getSetting() {
      var that = this;
      that.loading = true;
      api_GET_TrainReportTemplateSettingEntryCardSettingTrainningId(that.$route.params.id).then(res => {
        if (res && res.pageBackgroundImage) {
          that.form.backgroundStyle = {
            backgroundImage: 'url(' + that.getStaticFileUrl(res.pageBackgroundImage) + ')',
            backgroundRepeat: 'no-repeat',
            backgroundSize: '100% 100%'
          };
          that.$refs.certificate.style.backgroundImage = that.form.backgroundStyle.backgroundImage;
        }
        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: '获取参训证设置失败 ' + error.error.message });
      });
    },
    // 恢复原图
    resetImage() {
      var that = this;
      that.resetLoading = true;
      api_DELETE_TrainReportTemplateSettingEntryCardSettingTrainningId(that.$route.params.id).then(res => {
        if (res) {
          that.getSetting();
          that.$message({ type: 'success', message: '已恢复默认设置' });
        }
        that.resetLoading = false;
      }).catch(error => {
        that.resetLoading = false;
        that.$message({ type: 'error', message: '恢复默认设置失败 ' + error.error.message });
      });
    },
    // 上传图片限制
    check(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 < 800;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG或者PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 800kb!');
      }
      return isJPG && isLt2M;
    },
    // 上传文件之前，检查
    beforeUpload(file) {
      const checkData = this.check(file);
      if (checkData) {
        this.file = file;
      } else {
        return false;
      }
    },
    // 上传图片
    upload() {
      var that = this;
      this.uploadLoading = true;
      return new Promise((resolve, reject) => {
        if (!that.file) reject(new Error());
        const form = new FormData();
        form.append('formFile', that.file);
        that.uploadApi(that.action, form).then(res => {
          if (res.status === 200) {
            that.uploadLoading = false;
            that.$refs.certificate.style.backgroundImage = 'url(' + that.getStaticFileUrl(res.data.tempUrl) + ')';
            // 上传成功后自动保存
            that.updateSetting(res.data.tempUrl);
            resolve(res.data);
          } else {
            that.uploadLoading = false;
            reject(res.data);
          }
        });
      });
    },
    // 上传图片的api
    uploadApi(url, file) {
      const config = {
        headers: {
          Authorization: 'Bearer ' + this.tokenInfo
        }
      };
      return axios.post(url, file, config);
    },
    // 更新设置
    updateSetting(url) {
      var that = this;
      that.loading = true;
      const form = {
        trainningId: that.$route.params.id,
        pageBackgroundImage: url
      };
      api_PUT_TrainReportTemplateSettingEntryCardSetting(form).then(res => {
        if (res) {
          that.getSetting();
          that.$message({ type: 'success', message: '更新成功' });
        }
        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: '更新设置失败 ' + error.error.message });
      });
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 生成模板
    exportTemplate() {
      var that = this;
      this.buLoading = true;
      const tempUrl = `/api/app/Train/report/entryCards`;
      const fileName = '参训证' + '.zip';
      const params = {};
      params.ReportName = 'ExamCertificate';
      params.Format = 'PDF';
      params.ExportAll = true;
      params.FileDownloadName = '参训证';
      params.TrainningId = that.$route.params.id;
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, params, WEB_CONFIG.VUE_APP_SWAGGER_TRAIN_BASE).then(res => {
        that.buLoading = false;
      }).catch(error => {
        that.buLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.train {
  width: 1150px;
}
.box {
  width: 394px;
  display: inline-block;
}
.certificate {
  width: 394px;
  height: 583px;
  position: relative;
  border: 1px solid #d9d9d9;
  text-align: center;
  display: inline-block;
  color: #ffffff;
  .img_box {
    width: 100px;
    height: 126px;
    position: absolute;
    top: 140px;
    left: 50%;
    transform: translateX(-50%);
  }
  img {
    width: 100%;
    height: 100%;
  }
  .info {
    width: 304px;
    font-size: 18px;
    font-family: 'SimHei';
    color: #000;
    font-weight: bold;
    line-height: 32px;
    text-align: left;
    position: absolute;
    top: 324px;
    left: 50%;
    transform: translateX(-50%);
  }
}
.control {
  width: 720px;
  display: inline-block;
  vertical-align: top;
  margin-left: 30px;
  .title_name {
    color: #666666;
    line-height: 34px;
  }
  .box {
    border: 1px solid #dbdbdb;
    border-radius: 7px;
    padding: 20px;
    width: 590px;
  }
}
</style>
